<?php
use think\exception\HttpResponseException;
// 引入错误编码
include_once APP_PATH.'errcode.php';
// 引入自定义的define
include_once 'define.php';


function responseJson($data = [],$code = 0)
{
    $msg =  $GLOBALS['ERR_CODE'][$code] ? $GLOBALS['ERR_CODE'][$code] : '';
    throw new HttpResponseException(json(['code'=>$code,'msg'=> $msg,'data'=>$data]));
}
// 应用公共文件
function upload($data){
    if (strpos($data,'video')){
        $cover = UPLOAD_PATH.'uploads'.DS.date('Ymd').DS.time().rand(1000,9999).'.mp4';
        $data = explode(',',$data);
        $str = base64_decode($data[1]);
        if (!$str)
            responseJson([],996);
        // 获取表单上传文件;
        $tmp =  file_exists(UPLOAD_PATH.'uploads');
        //判断uploads文件夹是否存在
        if (!$tmp)
            mkdir(UPLOAD_PATH.'uploads');
        //判断文件夹是否存在
        if (!file_exists(UPLOAD_PATH.'uploads'.DS.date('Ymd')))
            mkdir(UPLOAD_PATH.'uploads'.DS.date('Ymd'));
        //文件写入
        $tmp = file_put_contents($cover,$str);
        //判断是否上传成功
        if (!$tmp)
            responseJson([],2011);
        $images =  str_replace(dirname(ROOT_PATH),'',$cover);
        return $images;
    }else{
        $cover = UPLOAD_PATH.'uploads'.DS.date('Ymd').DS.time();
        $data = explode(',',$data);
        foreach ($data as $key=>$val){
            if (strlen($val) > 25){
                $image[] = $val;
            }
        }
        if (empty($image)){
            responseJson([],1001);
        }
        foreach ($image as $value){
            $str = base64_decode($value);
            if (!$str)
                responseJson([],996);
            // 获取表单上传文件;
            $tmp =  file_exists(UPLOAD_PATH.'uploads');
            //判断uploads文件夹是否存在
            if (!$tmp)
                mkdir(UPLOAD_PATH.'uploads');
            //判断文件夹是否存在
            if (!file_exists(UPLOAD_PATH.'uploads'.DS.date('Ymd')))
                mkdir(UPLOAD_PATH.'uploads'.DS.date('Ymd'));
            //文件写入
            $num =   rand(1000,9999);
            $tmp = file_put_contents($cover.$num.'.png',$str);
            //判断是否上传成功
            if (!$tmp)
                responseJson([],2011);
            $images[] =  str_replace(dirname(ROOT_PATH),'',$cover.$num.'.png');

        }
        return $images;
   }
}
/*生成20位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NN,NN-CC，其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNN=随机数，CC=检查码
*/
function order_number()
{

    // @date_default_timezone_set("PRC");
    //订单号码主体（YYYYMMDDHHIISSNNNNNN）
    $order_id_main = date('YmdHis') . rand(1000, 9999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    return $order_id;
}
/**
 * 二维数组排序
 * $array 要排序的数组
 * $row  排序依据列
 * $type 排序类型[为2asc or 为1desc]
 * return 排好序的数组
 */
function array_sort($array,$row,$type){
    $array_temp = [];
    foreach ($array as $key => $val){
        $num = $val[$row] * 10;
        $array_temp[$num] = $val;
    }
    print_r($array_temp);exit;
    //升序排列
    if($type == 2){
        ksort($array_temp);
    }
    //降序排列
    if($type == 1){
        krsort($array_temp);
    }
    $array_temp = array_values($array_temp);
    return $array_temp;
}
//自己封装的随机生成的盐函数
function salt()
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $salt = '', $lc = strlen($chars)-1; $i < 4; $i++) {
        $salt .= $chars[mt_rand(0, $lc)];
    }
    return $salt;
}

function http_get($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $output = curl_exec($ch);
    curl_close($ch);
    $arr_out = json_decode($output);
    return $arr_out;
}
/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$param,$post_file=false){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
    }
    if (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach($param as $key=>$val){
            $aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}


/**
 * 计算两点地理坐标之间的距离
 * @param  Decimal $longitude1 起点经度
 * @param  Decimal $latitude1  起点纬度
 * @param  Decimal $longitude2 终点经度
 * @param  Decimal $latitude2  终点纬度
 * @param  Int     $unit       单位 1:米 2:公里
 * @param  Int     $decimal    精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

/*
 * 设置用户等级
 * @param int $exp 经验值
 */
function getLevel($exp)
{
    include_once APP_PATH.'level.php';
    $level = $GLOBALS['level'];//获取经验等级
    //判断用户的等级
    foreach ($level as $key=>$val){
        if ($val <= $exp){
            $grade = $key;
        }
    }
    return $grade;
}

/*
 *分页
 * @param array $list  数据
 * @param int   $page  页码
 * @param int   $num   一页多少条记录
 */
function paging($list,$page,$num = 10)
{
    $start = ($page - 1)*$num;
    $total = sizeof($list);
    $data = array_slice($list,$start,$num);
    $Data = [
        'total' => $total,
        'data'  =>  $data,
    ];
    return $Data;
}

function getfirstchar($s0){
    $fchar = ord($s0{0});
    if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
    //$s1 = iconv("UTF-8","gb2312//IGNORE", $s0);
    //$s2 = iconv("gb2312","UTF-8//IGNORE", $s1);
    $s1 = get_encoding($s0,'GB2312');
    $s2 = get_encoding($s1,'UTF-8');
    if($s2 == $s0){$s = $s1;}else{$s = $s0;}
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284)
        return 'A';

    if ($asc >= -20283 && $asc <= -19776)
        return 'B';

    if ($asc >= -19775 && $asc <= -19219)
        return 'C';

    if ($asc >= -19218 && $asc <= -18711)
        return 'D';

    if ($asc >= -18710 && $asc <= -18527)
        return 'E';

    if ($asc >= -18526 && $asc <= -18240)
        return 'F';

    if ($asc >= -18239 && $asc <= -17923)
        return 'G';

    if ($asc >= -17922 && $asc <= -17418)
        return 'H';

    if ($asc >= -17417 && $asc <= -16475)
        return 'J';

    if ($asc >= -16474 && $asc <= -16213)
        return 'K';

    if ($asc >= -16212 && $asc <= -15641)
        return 'L';

    if ($asc >= -15640 && $asc <= -15166)
        return 'M';

    if ($asc >= -15165 && $asc <= -14923)
        return 'N';

    if ($asc >= -14922 && $asc <= -14915)
        return 'O';

    if ($asc >= -14914 && $asc <= -14631)
        return 'P';

    if ($asc >= -14630 && $asc <= -14150)
        return 'Q';

    if ($asc >= -14149 && $asc <= -14091)
        return 'R';

    if ($asc >= -14090 && $asc <= -13319)
        return 'S';

    if ($asc >= -13318 && $asc <= -12839)
        return 'T';

    if ($asc >= -12838 && $asc <= -12557)
        return 'W';

    if ($asc >= -12556 && $asc <= -11848)
        return 'X';

    if ($asc >= -11847 && $asc <= -11056)
        return 'Y';

    if ($asc >= -11055 && $asc <= -10247)
        return 'Z';

    return null;
}
/**
 * @name: get_encoding
 * @description: 自动检测内容编码进行转换
 * @param: string data
 * @param: string to  目标编码
 * @return: string
 **/
function get_encoding($data,$to){
    $encode_arr=array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
    $encoded=mb_detect_encoding($data, $encode_arr);
    $data = mb_convert_encoding($data,$to,$encoded);
    return $data;
}


/**
 * 无限极树形遍历
 */
function tree($array, $parentid = 0)
{
    $result = array();
    foreach ($array as $val) {
        if ($val["pid"] == $parentid) {
            $indata = array("data" => $val);

            $chidrendata = tree($array, $val["id"]);
            if ($chidrendata) {
                $indata["children"] = $chidrendata;
            }
            $result[] = $indata;
        }
    }
    return $result;
}

//function pinyin1($zh){
//    $ret = "";
//    $s1 = iconv("UTF-8","gb2312", $zh);
//    $s2 = iconv("gb2312","UTF-8", $s1);
//    if($s2 == $zh){$zh = $s1;}
//    for($i = 0; $i < strlen($zh); $i++){
//        $s1 = substr($zh,$i,1);
//        $p = ord($s1);
//        if($p > 160){
//            $s2 = substr($zh,$i++,2);
//            $ret = getfirstchar($s2);
//        }else{
//            $ret = $s1;
//        }
//    }
//    return $ret;
//}
